<template>
  <div class="user-profile">
    <van-nav-bar
      title="个人资料"
      left-text="返回"
      left-arrow
      @click-left="router.back()"
    />

    <van-cell-group inset class="avatar-group">
      <van-cell title="头像" center>
        <template #right-icon>
          <van-uploader
            v-model="fileList"
            :max-count="1"
            :before-read="beforeAvatarUpload"
            :after-read="afterAvatarUpload"
          >
            <van-image
              round
              width="50"
              height="50"
              :src="userInfo.avatar || defaultAvatar"
            />
          </van-uploader>
        </template>
      </van-cell>
    </van-cell-group>

    <van-cell-group inset>
      <van-cell title="用户名" :value="userInfo.username" />
      <van-cell
        title="姓名"
        :value="userInfo.realName"
      />
      <van-cell
        title="性别"
        :value="genderText"
        @click="showGenderPicker = true"
      />
      <van-cell
        title="年龄"
        :value="userInfo.age"
      />
      <van-cell
        title="手机号"
        :value="userInfo.phone"
      />
    </van-cell-group>

    <van-cell-group inset>
      <van-cell
        title="修改密码"
        is-link
        @click="showPasswordDialog = true"
      />
    </van-cell-group>

    <!-- 编辑弹窗 -->
    <van-dialog
      v-model:show="showEditDialog"
      :title="editTitle"
      show-cancel-button
      @confirm="handleEditConfirm"
    >
      <van-field
        v-model="editValue"
        :placeholder="editPlaceholder"
        :type="editType"
      />
    </van-dialog>

    <!-- 性别选择器 -->
    <van-popup v-model:show="showGenderPicker" position="bottom">
      <van-picker
        :columns="genderColumns"
        @confirm="onGenderConfirm"
        @cancel="showGenderPicker = false"
      />
    </van-popup>

    <!-- 修改密码弹窗 -->
    <van-dialog
      v-model:show="showPasswordDialog"
      title="修改密码"
      show-cancel-button
      @confirm="handlePasswordChange"
    >
      <van-field
        v-model="passwordForm.oldPassword"
        type="password"
        label="原密码"
        placeholder="请输入原密码"
      />
      <van-field
        v-model="passwordForm.newPassword"
        type="password"
        label="新密码"
        placeholder="请输入新密码"
      />
      <van-field
        v-model="passwordForm.confirmPassword"
        type="password"
        label="确认密码"
        placeholder="请再次输入新密码"
      />
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { useUserStore } from '@/stores/user'
import { getUserInfo, updateUserInfo, changePassword, uploadAvatar } from '@/api/user'
import defaultAvatar from '@/assets/default-avatar.png'

const router = useRouter()
const userStore = useUserStore()

const userInfo = ref({})
const fileList = ref([])
const showEditDialog = ref(false)
const showGenderPicker = ref(false)
const editField = ref('')
const editValue = ref('')
const editTitle = ref('')
const editType = ref('text')
const editPlaceholder = ref('')

const genderColumns = [
  { text: '男', value: 1 },
  { text: '女', value: 2 }
]

// 密码修改
const showPasswordDialog = ref(false)
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 计算属性
const genderText = computed(() => userInfo.value.gender === 1 ? '男' : '女')
const heightText = computed(() => userInfo.value.height ? `${userInfo.value.height}cm` : '未设置')
const weightText = computed(() => userInfo.value.weight ? `${userInfo.value.weight}kg` : '未设置')

// 获取用户信息
const loadUserInfo = async () => {
  try {
    const { data } = await getUserInfo()
    userInfo.value = data
  } catch (error) {
    showToast('获取用户信息失败')
  }
}

// 显示编辑弹窗
const showEditField = (field) => {
  editField.value = field
  editValue.value = userInfo.value[field] || ''

  switch (field) {
    case 'nickname':
      editTitle.value = '修改昵称'
      editType.value = 'text'
      editPlaceholder.value = '请输入昵称'
      break
    case 'height':
      editTitle.value = '修改身高'
      editType.value = 'number'
      editPlaceholder.value = '请输入身高(cm)'
      break
    case 'weight':
      editTitle.value = '修改体重'
      editType.value = 'number'
      editPlaceholder.value = '请输入体重(kg)'
      break
  }

  showEditDialog.value = true
}

// 确认编辑
const handleEditConfirm = async () => {
  try {
    await updateUserInfo({ [editField.value]: editValue.value })
    userInfo.value[editField.value] = editValue.value
    showToast('修改成功')
  } catch (error) {
    showToast('修改失败')
  }
}

// 性别选择确认
const onGenderConfirm = async (value) => {
  try {
    await updateUserInfo({ gender: value.value })
    userInfo.value.gender = value.value
    showGenderPicker.value = false
    showToast('修改成功')
  } catch (error) {
    showToast('修改失败')
  }
}

// 修改密码
const handlePasswordChange = async () => {
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    showToast('两次输入的密码不一致')
    return
  }

  try {
    await changePassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })
    showToast('密码修改成功')
    showPasswordDialog.value = false
    // 清空表单
    passwordForm.oldPassword = ''
    passwordForm.newPassword = ''
    passwordForm.confirmPassword = ''
  } catch (error) {
    showToast('密码修改失败')
  }
}

// 头像上传相关
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    showToast('只能上传图片文件')
  }
  return isImage
}

const afterAvatarUpload = async (file) => {
  const formData = new FormData()
  formData.append('avatar', file.file)

  try {
    const { data } = await uploadAvatar(formData)
    userInfo.value.avatar = data.url
    userStore.setAvatar(data.url)
    showToast('头像上传成功')
  } catch (error) {
    showToast('头像上传失败')
  }
}

onMounted(() => {
  loadUserInfo()
})
</script>

<style lang="scss" scoped>
.user-profile {
  min-height: 100vh;
  background-color: #f7f8fa;

  .avatar-group {
    margin: 12px 0;
  }

  .van-cell-group {
    margin-bottom: 12px;
  }
}
</style>
